package com.xc.common.interceptor;

import com.google.common.collect.Maps;
import com.xc.pojo.User;
import com.xc.utils.PropertiesUtil;
import com.xc.utils.redis.CookieUtils;
import com.xc.utils.redis.JsonUtil;
import com.xc.utils.redis.RedisShardedPoolUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;
/**
 *  用户登陆拦截器
 * Created by xiongcan on 2018/1/25.
 */
@Slf4j
public class ApiUserAuthorityInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest
            , HttpServletResponse httpServletResponse, Object handler) throws Exception {

//        log.info("请求进入 ApiUserAuthorityInterceptor...");

        //  开始处理业务逻辑-----------------------------------------------------------------------
        User user = null;
        String loginToken = CookieUtils
                .readLoginToken(httpServletRequest
                        , PropertiesUtil.getProperty("user.cookie.name"));
//        log.info("user loginToken = {}" , loginToken);

        if(StringUtils.isNotEmpty(loginToken)){
            String userJsonStr = RedisShardedPoolUtils.get(loginToken);
//            log.info("================拦截器拦截到user ：{}===================",userJsonStr);
            user = JsonUtil.string2Obj(userJsonStr , User.class);
        }

        if(null == user){
            log.info("authority: user 为空");

            //  首先重置response,否则会报异常 getWriter() has been called for this response;
            httpServletResponse.reset();
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json;charset=UTF-8");

            PrintWriter writer = httpServletResponse.getWriter();

            Map map = Maps.newHashMap();
            map.put("success" , false);
            map.put("msg" , "请先登录，无权限访问user");
            writer.print(JsonUtil.obj2String(map));

            writer.flush();
            writer.close();
            //  返回false，不会进入controlelr
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, ModelAndView modelAndView) throws Exception {
//        log.info("=============================postHandle=============================");
    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception e) throws Exception {
//        log.info("=============================afterCompletion=============================");
    }



}
